package com.app.newcsc.fragment.moneydetail;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.databinding.FragmentFundMoneyDetailBinding;
import com.app.newcsc.entity.WalletEntity;
import com.app.newcsc.entity.WalletTypeEntity;
import com.app.newcsc.utils.NumberUtils;
import com.app.newcsc.utils.SpUtils;
import com.app.newcsc.view.CustomPopWindow;
import com.app.newcsc.view.WalletTypesAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * @author: woking
 * @date: 2021/6/12
 * @description：
 */
public class MoneyDetailFragment extends BaseFragment<FragmentFundMoneyDetailBinding, FundMoneyDetailViewModel> {
    private WalletEntity mWalletEntity = null;
    private String type = "3";//AD
    @Override
    public void initParam() {
        super.initParam();
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_fund_money_detail;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public FundMoneyDetailViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FundMoneyDetailViewModel.class);
    }

    @Override
    public void initData() {
        viewModel.filterType.setValue("");
        viewModel.fundMoneyDetailType.setValue("");//coid id
        if (getArguments() != null) {
            mWalletEntity = (WalletEntity)getArguments().getSerializable("data");
            type = getArguments().getString("type");
            viewModel.fundMoneyDetailType.setValue(type);
            Log.e("TAG","===============initData========type========="+type);
        }

        if(mWalletEntity != null) {
            binding.typeTv.setText(mWalletEntity.coin_name+"总额");
            binding.adNum.setText(NumberUtils.keepPrecision(mWalletEntity.money,4));
            binding.dongjieTv.setText("冻结: "+NumberUtils.keepPrecision(mWalletEntity.freeze,4)+mWalletEntity.coin_name);

            Map<String,String> bill_types = mWalletEntity.bill_types;
            if(bill_types != null)
            {
                for (Map.Entry<String, String> entry : bill_types.entrySet())
                {
                    WalletTypeEntity mwalletTypeEntity = new WalletTypeEntity();
                    mwalletTypeEntity.type = entry.getKey();
                    mwalletTypeEntity.title = entry.getValue();
                    viewModel.walletTypeEntityList.add(mwalletTypeEntity);
                }
            }
        }

        binding.myrecyclerview.setEmptyView(binding.emptyView);

        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
        binding.setAdapter(new BindingRecyclerViewAdapter());

        //请求网络数据
        viewModel.requestNetWork(false);
//        viewModel.otcBillTypes();

        initRefreshLayout();

        binding.guolvImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initPOP(view);
            }
        });
        binding.ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
    }
    private void initRefreshLayout()
    {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.onRefresh();
            }
        });
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.onLoadMore();
            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
//                binding.twinklingRefreshLayout.finishRefreshing();
                binding.twinklingRefreshLayout.finishRefresh();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
//                binding.twinklingRefreshLayout.finishLoadmore();
                binding.twinklingRefreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SpUtils.put(getActivity(),"isLogin","");
    }

    private CustomPopWindow mCustomPopWindow;
    private void initPOP(View view)
    {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_money_detail,null);
        ListView listView = contentView.findViewById(R.id.listview_list);
        WalletTypesAdapter adapter = new WalletTypesAdapter(getContext(),viewModel.walletTypeEntityList );
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("TAG", "=======initPOP========"+ viewModel.walletTypeEntityList.get(i).title);
                if(i == 0)
                {
                    viewModel.filterType.setValue("");
                }
                else
                {
                    viewModel.filterType.setValue(viewModel.walletTypeEntityList.get(i).type+"");
                }
                mCustomPopWindow.dissmiss();
                viewModel.requestNetWork(false);
            }
        });

        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.3f) // 控制亮度
                .setFocusable(true)
                .setOutsideTouchable(true)
//                .size(600,400) //设置显示的大小，不设置就默认包裹内容
                .size(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM,0,20);
//                .showAsDropDown(view,0,20);
    }
}